<?php

class Db_Solr {

    static function doSearch($keyword, $limitStart = 0, $limit = 50, $type = 0, $param_ = array(), $uparam =array(), $sort='') {
        require_once('SolrPhpClient/Apache/Solr/Service.php');

        $solr = new Apache_Solr_Service(SOLR_SERVER_HOST, SOLR_SERVER_PORT, SOLR_SERVER_SEARCH);

        $fq = " status:1 ";

        $fieldList = "id,name,star,city_name,latitude,longitude,rating_0_0_count,rating_0_0_average,rating_star,desc,image_default,price_min";

        $query = $keyword;

        if ($param_) {
            foreach ($param_ as $key => $p) {
                $fq .= " AND $key:$p ";
            }
        }
        if ($uparam){
            $temp ='';
            $arrTem = array();
            foreach ($uparam as $up){
                if(!in_array($up->hotel_id,$arrTem) && sizeof($arrTem) < $limit){
                    $temp .= 'id:'.$up->hotel_id .' OR ';
                    $arrTem[] = $up->hotel_id ;
                }

            }
            //var_dump($arrTem);die;
            $temp = substr($temp,0,-3);
            $fq .= " AND ( ".$temp." )";
        }
        if ($type == 1) { // Show total item per Category
            $params_search = array();

            $params_search['facet'] = 'true';
            $params_search['facet.mincount'] = 1;
            $params_search['facet.field'] = 'level_1_category_id';
            $params_search['fq'] = $fq;
            $params['fl'] = $fieldList;
            $params['fl'] = 'id,name';
            $params_search['wt'] = 'json';
            $params_search['qt'] = QT_SOLR;
            $response = $solr->search($query, 0, 0, $params_search);
        } else {
            $params = array();
            $params['hl'] = 'on';
            $params['hl.fl'] = 'name';
            $params['qt'] = '/bookingSearch'; //su dung config file
            $params['fq'] = $fq;
            $params['fl'] = $fieldList;
            $params['wt'] = 'json';
            if($sort != '')
                $params['sort'] = $sort;
           // var_dump($query, $limitStart, $limit, $params);die;
            $response = $solr->search($query, $limitStart, $limit, $params);
        }

        if ($response) {

            if ($response->getHttpStatus() == 200) {
                return $response;
            }
        }

        return null;
    }

    static function suggestion($keywords) {
        //include "BootStrap.php";

        $params['spellcheck.q'] = $keywords;
        $params['wt'] = 'json';
        $total = 0;

        $url = 'http://' . SOLR_SERVER_HOST . ':' . SOLR_SERVER_PORT . SOLR_SERVER_SUGGEST . '/suggest?';

        $queryString = http_build_query($params, null, '&');

        $queryString = preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '=', $queryString);

        $_getContext = stream_context_create();

        stream_context_set_option($_getContext, 'http', 'timeout', 2);

        $arr_solr = @file_get_contents($url . $queryString, false, $_getContext);

        if ($arr_solr) {
            $results = json_decode($arr_solr)->{"spellcheck"}->{"suggestions"};
        }

        if ($results) {
            $total = $results[1]->{"numFound"};
        }

        if ($total) {
            return $results[1]->{"suggestion"};
        } else {
            return null;
        }
    }

    static function autocomplete($keywords) {
        //include "BootStrap.php";
        // $params = array(
        // 'terms'=>'true',
        // 'terms.fl'=>'name',
        // 'terms.regex' => '(.*)' . $keyword . '(.*)',
        //'terms.regex.flag' => 'dotall',
        //'terms.prefix'=>$keywords,            
        // 'wt'=>'json',
        // 'sort'=>'count',
        // 'terms.limit'=>"10",
        // 'indent'=>'on',
        // 'omitHeader'=>'true'			
        // );

        $params = array(
            'terms' => 'true',
            'terms.fl' => 'autocomplete',
            'omitHeader' => 'true',
            'terms.regex' => '.*' . $keywords . '.*',
            'terms.regex.flag' => 'dotall',
            'terms.sort' => 'count',
            'terms.limit' => '6',
            'wt' => 'json'
        );

        $url = 'http://' . SOLR_SERVER_HOST . ':' . SOLR_SERVER_PORT . SOLR_SERVER_SUGGEST . '/terms?';

        $queryString = http_build_query($params, null, '&');

        $queryString = preg_replace('/%5B(?:[0-9]|[1-9][0-9]+)%5D=/', '=', $queryString);

        $_getContext = stream_context_create();

        stream_context_set_option($_getContext, 'http', 'timeout', 2);

        $results = @file_get_contents($url . $queryString, false, $_getContext);
        //echo $url.$queryString;

        if ($results) {
            return json_decode($results)->{"terms"}->{"autocomplete"};
        }

        return null;
    }

    static function getcheckRoom($time,$offset=0,$limit=1,$hotel_id = false) {//get room which have no available
        require_once('SolrPhpClient/Apache/Solr/Service.php');
        $solr = new Apache_Solr_Service(SOLR_SERVER_HOST, SOLR_SERVER_PORT, SOLR_SERVER_CHECKROOM);
        $fieldList = 'room_id';
        $params = array();
        $params['fl'] = $fieldList;
        $query_hotel = '';
        if($hotel_id){
           // $query_hotel .= ' AND (';
            foreach($hotel_id as $id){
                $query_hotel .= 'hotel_id:'.$id->id .' OR ';
            }
            $query_hotel = substr($query_hotel,0,-3);
            $query_hotel = 'AND ( '.$query_hotel.' )';
        }
        $query = "(check_time: $time OR check_time:0) AND status:1 " .$query_hotel;
        //var_dump($query);die;
        $response = $solr->search($query,$offset,$limit,$params);
        return $response;
    }
    static function getRoombyPrice($time,$offset=0,$limit=1,$price='') {//get room out of price
        require_once('SolrPhpClient/Apache/Solr/Service.php');
        $solr = new Apache_Solr_Service(SOLR_SERVER_HOST, SOLR_SERVER_PORT, SOLR_SERVER_CHECKROOM);
        $fieldList = 'room_id';
        $params = array();
        $params['fl'] = $fieldList;
        $query = " check_time: $time ";
        if($price !='')
            $query .= 'AND !price:'.$price;
        $response = $solr->search($query,$offset,$limit,$params);
        return $response;
    }
//    static function getRoombyPrice($time,$offset=0,$limit=1,$price = '') {//lấy phòng có giá phù hợp trong check_room
//        require_once('SolrPhpClient/Apache/Solr/Service.php');
//        $solr = new Apache_Solr_Service('192.168.7.127', 7979, '/solr/CheckRoom/');
//        $fieldList = 'hotel_id';
//        $params = array();
//        $params['fl'] = $fieldList;
//        $query = "check_time: $time AND status:1";
//        if($price != '')
//            $query .= 'price:'.$price;
//        $response = $solr->search($query,$offset,$limit,$params);
//        return $response;
//    }
    static function getRoombyCheck($offset=0,$limit=1,$uparams=array(),$condition='') {//get room which have no available
        require_once('SolrPhpClient/Apache/Solr/Service.php');
        $solr = new Apache_Solr_Service(SOLR_SERVER_HOST, SOLR_SERVER_PORT, SOLR_SERVER_ROOM);
        $fieldList = 'hotel_id';
        $params = array();
        $params['fl'] = $fieldList;
        $query = "status:1";
        if($condition != '')
            $query .= " AND price: $condition ";
        if ($uparams) {
            //var_dump($uparams);die;
            foreach ($uparams as $p) {
            //var_dump($p);die;
                foreach($p as $rom){
                    $query .= " AND !id:$rom->room_id ";
                }

            }
        }

        $response = $solr->search($query,$offset,$limit,$params);
        return $response;
    }

}

?>